#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPluginLoader>
#include <QDesignerCustomWidgetInterface>
#include<QApplication>
#include<QHBoxLayout>
#include<QPushButton>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QWidget* pPluginWidget = loadplugin();
    if(pPluginWidget)
    {
        QHBoxLayout* l = new QHBoxLayout();
        l->addWidget(pPluginWidget);
        ui->centralwidget->setLayout(l);

        QPushButton* p = new QPushButton(this);
        p->setText("Reset");
        l->addWidget(p);
        if( connect(p, SIGNAL(pressed()), pPluginWidget, SLOT(ResetTimer())))
        {
            qDebug("connect sussucess");
        }
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

//加载插件函数
QWidget *loadPlugins(QString pluginFileName, QWidget *parent)
{
    QPluginLoader loader( pluginFileName );

    bool b = loader.load();
    if(b)
        qDebug("loder ok!\r\n");
    else
        qDebug("loder error!\r\n");

    QObject *plugin = loader.instance();
    if (plugin)
    {
        QDesignerCustomWidgetInterface *iCustomWidgetInterface = qobject_cast<QDesignerCustomWidgetInterface *>(plugin);
        if( iCustomWidgetInterface ){
            QWidget *widget = iCustomWidgetInterface->createWidget( parent );
            return widget;
        }
    }
    else
        qDebug("loader.instance() error\r\n");

    return NULL;
}
//初始化插件
QWidget* MainWindow::loadplugin()
{
    QString DirPath=QCoreApplication::applicationDirPath();
    DirPath=DirPath.left(DirPath.lastIndexOf("/"));
    QString pluginfilename;
    pluginfilename = DirPath+"/../testPlugin/dll/debug/testpluginplugind.dll";
    return loadPlugins( pluginfilename, this );
}
